package telsoft.app.form;

import java.awt.*;
import java.awt.event.*;
import java.util.*;

import javax.swing.*;
import javax.swing.event.*;

import jxl.*;
import telsoft.admin.util.*;
import telsoft.app.util.*;
import telsoft.comm.protocol.*;
import telsoft.swing.*;
import telsoft.util.*;
import java.text.SimpleDateFormat;

public class FormTransport extends JXFrame implements ControlButtonListener {
    public VectorTable tblValue = new VectorTable();
    public VectorTable tblnumber = new VectorTable();
    public VectorTable tblValue2 = new VectorTable();
    public JXText imsi_p = new JXText();
    public JXDatePlus start_date = new JXDatePlus();
    public JXDatePlus finish_date = new JXDatePlus();
    public JButton btnLoad;
    public JButton btnRefresh;
    public PanelControlButton pnbutton;
    public PanelCommonLOV area;
    public FormTransport() throws Exception {
        payInit();
    }

    private void payInit() throws Exception {
        buildForm();
        tblValue = (VectorTable) formData.getControl("tblReg");
        tblValue2 = (VectorTable) formData.getControl("tblListTrans");
	tblnumber = (VectorTable) formData.getControl("tblListNumber");
        btnLoad = (JButton) formData.getControl("btnLoad");
        btnRefresh = (JButton) formData.getControl("btnRefresh");
        area = (PanelCommonLOV) formData.getField("Area");
        imsi_p = (JXText) formData.getField("Imsi_prefix");
        start_date = (JXDatePlus) formData.getField("dtStartDate");
        finish_date = (JXDatePlus) formData.getField("dtFinishDate");
        pnbutton = (PanelControlButton) formData.getLayout("ControlButton");
        pnbutton.setNormalState();
        //su kien click chuot vao dong, goi ham fill du lieu vao textbox
        tblValue2.getSelectionModel().
                addListSelectionListener(new ListSelectionListener() {
            public void valueChanged(ListSelectionEvent e) {
                if (e.getValueIsAdjusting()) {
                    return;
                }
                fillDetailValue();
            }

        });
        onChangeAction(ACTION_NONE, ACTION_NONE);
        FillDialogData();
        Skin.applySkin(this);
        loadForm();
        loadForm2();
        //Xu ly nhan button import data
        btnLoad.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                importData(); // goi den ham importData()
            }
        });
        btnRefresh.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e){
	       Refresh(); // goi den ham dong bo du lieu
            }
        });

    }

    public void importData() {
        try {
            String strFilename = Util.openFile(this); //Goi ham openFile nham lay duoc duong dan file xls nguoi dung chon
            if (strFilename != null) { //kiem tra gia tri, neu nguoi dung da chon (tuc strFilename != null)
                Vector vtData = new Vector();
                vtData = getExcelData(strFilename); //goi den ham getExcelData de doc du lieu
                if (vtData == null || vtData.size() < 0) { //kiem tra xem vtdata co gia tri hay khong, tuc file co chua du lieu hay khong
                    return;
                }
                DataTransmit datr = new DataTransmit();
                this.setCursor(Cursor.getPredefinedCursor(Cursor.
                        WAIT_CURSOR));
                datr.setVector("mvtData", vtData); //lay ve vector du lieu de truyen sang cho bean
                DataTransmit prmResponse = AppClient.sendRequest(
                        "telsoft.app.bean.TransportBean",
                        "importData", datr);
                Vector vtErrData = prmResponse.getVector("vtErrData2"); //vterrdata la ben bean day ve vector chua loi
                String strSuccess = prmResponse.getString("isuccess"); //so ban ghi thanh cong
                String strMsg = getDictionary().getString("success") +
                                strSuccess + "/" +
                                vtData.size() + "\n";
                loadForm(); //goi lai ham loadform de xem hien thi
                if (vtErrData.size() > 0) { //Neu co loi thi goi ham writeLogFile trong file Util.java
                    Util.writeLogFile(strFilename.substring(0,
			    strFilename.lastIndexOf(".xls")) + "_" +
				    new java.text.
				    SimpleDateFormat("yyMMddHHmmss").format(new
		    java.util.Date()) + ".txt",
                                      vtErrData);
                    strMsg += getDictionary().getString("Error");
                    // ".\nCó lỗi khi xử lý import. Xem file log cùng thư mục với file danh sách.";
                }
                this.setCursor(Cursor.getPredefinedCursor(Cursor.
                        DEFAULT_CURSOR));
                MessageBox.showMessageDialog(this, strMsg, Global.APP_NAME,
                                             MessageBox.WARNING_MESSAGE);
            }
        } catch (Exception e) {
            MessageBox.showMessageDialog(this, e.getMessage(),
                                         Global.APP_NAME);
            this.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
        }
    }

    public Vector getExcelData(String strFileName) throws Exception { //Lay tung dong du lieu luu vao mang vtData
        Workbook w1 = null;
        String strCellValue = "";
        Cell cell = null;
        Vector vtData = new Vector();
        Vector vtRow = new Vector();
        try {
            w1 = Workbook.getWorkbook(new java.io.File(strFileName));
            Sheet sheet = w1.getSheet(0);
            int iCount = sheet.getRows(); //Lay ve so dong trong file
            for (int i = 0; i < iCount; i++) {
                vtRow = new Vector();
                for (int j = 0; j < 6; j++) {
                    cell = sheet.getCell(j, i); //lay gia tri tung phan tu
                    strCellValue = cell.getContents().trim();
                    vtRow.addElement(strCellValue); //add vao dong
                }
                vtData.addElement(vtRow); //add dong vao vtData
            }
            w1.close();
        } catch (Exception e) {
            e.printStackTrace();
            MessageBox.showMessageDialog(this, e.getMessage(), Global.APP_NAME,
                                         MessageBox.ERROR_MESSAGE);
        }
        return vtData; //tra ve vector
    }

    public void loadForm() { //Ham load form cho panel cap nhan thong tin kich hoat
        try {
            DataTransmit prmRequest = new DataTransmit();
            DataTransmit prmResponse = AppClient.sendRequest(
                    "telsoft.app.bean.TransportBean",
                    "loadForm", prmRequest);

            Vector vtResult = (Vector) prmResponse.getReturn();
            int iSelected = tblValue.getSelectedRow();
            tblValue.setData(vtResult); //day du lieu vao bang
            if (tblValue.getRowCount() > 0) {

                if (iSelected < 0 || iSelected >= tblValue.getRowCount()) {
                    iSelected = 0;
                }
                tblValue.setRowSelectionInterval(iSelected, iSelected);
            }
//	   checkControlButton();
        } catch (Exception e) {
            e.printStackTrace();
            MessageBox.showMessageDialog(this, e, Global.APP_NAME,
                                         MessageBox.ERROR_MESSAGE);
        }
    }

    public Boolean Refresh(){
        try {
	    DataTransmit request = new DataTransmit();
	    request.setString("abc","abc");
	    DataTransmit response = AppClient.sendRequest(
                    "telsoft.app.bean.TransportBean", "Refresh", request);
	    MessageBox.showMessageDialog(this,"Thông tin kích hoạt đã được cập nhật vào quản lý thuê bao",
		    Global.APP_NAME,MessageBox.INFORMATION_MESSAGE);
        } catch (Exception e) {
            e.printStackTrace();
            MessageBox.showMessageDialog(this, e, Global.APP_NAME,
                                         MessageBox.ERROR_MESSAGE);
//	    ISDN.requestFocus();
            return false;

        }
        return true;
    }

    public void FillDialogData() { //ham day du lieu vao dialog phuc vu cho tim kiem dia ban
        //lay ve tu ben bean du lieu ID va name nhe
        DataTransmit prmRequest = new DataTransmit();
        DataTransmit prmResponse = null;
        try {
            prmResponse = AppClient.sendRequest(
                    "telsoft.app.bean.TransportBean",
                    "FillDialog", prmRequest);
        } catch (Exception ex) {
        }

        Vector vtData = (Vector) prmResponse.getReturn();
        Vector vtCol = new Vector();
        vtCol.addElement("ID");
        vtCol.addElement("Area name");
        area.setCommonLov(this, vtCol, vtData);

    }

    public void loadForm2() { //Ham load form cho panel cap phat so thue bao
        try {
            DataTransmit prmRequest = new DataTransmit();
            DataTransmit prmResponse = AppClient.sendRequest(
                    "telsoft.app.bean.TransportBean",
                    "loadForm2", prmRequest);

            Vector vtResult2 = (Vector) prmResponse.getReturn();
            int iSelected = tblValue2.getSelectedRow();
            tblValue2.setData(vtResult2); //day du lieu vao bang
            if (tblValue2.getRowCount() > 0) {

                if (iSelected < 0 || iSelected >= tblValue2.getRowCount()) {
                    iSelected = 0;
                }
                tblValue2.setRowSelectionInterval(iSelected, iSelected);
            }
            checkControlButton();
        } catch (Exception e) {
            e.printStackTrace();
            MessageBox.showMessageDialog(this, e, Global.APP_NAME,
                                         MessageBox.ERROR_MESSAGE);
        }
    }

    public void checkControlButton() { //Ham kiem tra nut duoc chon
        pnbutton.btnAdd.setEnabled(true);
        if (tblValue2.getRowCount() <= 0) { //Neu nguoi dung khong chon truong nao thi dat an cac button
            pnbutton.btnAddCopy.setEnabled(false);
            pnbutton.btnModify.setEnabled(false);
            pnbutton.btnRemove.setEnabled(false);
        } else if (tblValue2.getRowCount() > 0) { //nguoc lai nen ND chon
            pnbutton.btnAddCopy.setEnabled(true);
            pnbutton.btnModify.setEnabled(true);
            pnbutton.btnRemove.setEnabled(true);
        }
    }

    //lay ngay gio he thong
    Date todayD = new Date(System.currentTimeMillis());

//Khai bao dinh dang ngay thang
    SimpleDateFormat dayFormat = new SimpleDateFormat("dd/MM/yyyy");

//parse ngay thang sang dinh dang va chuyen thanh string.
    String todayS = dayFormat.format(todayD.getTime());

    public void clearDetailValue() { //Ham xoa trang du lieu tai cac field
        try {
            formData.setFieldValue("Area", "");
            formData.setFieldValue("Imsi_prefix", "");
            formData.setFieldValue("dtStartDate", todayS);
            formData.setFieldValue("dtFinishDate", "");
            area.clearText();
        } catch (Exception ex) {
            ex.printStackTrace();
            MessageBox.showMessageDialog(this, ex, Global.APP_NAME,
                                         MessageBox.ERROR_MESSAGE);
        }
    }

    public void fillDetailValue() { //Day du lieu tu bang vao cac truong tren form khi click chuot
        int iSelected = tblValue2.getSelectedRow();
        if (iSelected < 0) {
            clearDetailValue();
            return;
        }
        Vector vtRowData = tblValue2.getRow(iSelected); //lay ve dong duoc chon, va day vao textbox
        try {
            area.txtCode.setText(vtRowData.elementAt(5).toString());
            area.txtName.setText(vtRowData.elementAt(1).toString());
            formData.setFieldValue("Imsi_prefix",
                                   vtRowData.elementAt(2).toString());
            formData.setFieldValue("dtStartDate",
                                   vtRowData.elementAt(3).toString());
            formData.setFieldValue("dtFinishDate",
                                   vtRowData.elementAt(4).toString());
	    //day danh sach thue bao sang bang chi tiet thue bao khi click bang
	    DataTransmit request = new DataTransmit();
	    //Lay gia tri tu form
	    request.setString("mstrID_area", area.getCode());
	    //day sang ben bean thuc hien truy van
	    DataTransmit response = AppClient.sendRequest(
		    "telsoft.app.bean.TransportBean", "getnumber", request);
	    Vector vtRow = (Vector) response.getReturn();
	    tblnumber.setData(vtRow);

        } catch (Exception ex) {
            ex.printStackTrace();
            MessageBox.showMessageDialog(this, ex, Global.APP_NAME,
                                         MessageBox.ERROR_MESSAGE);
        }
    }

    public boolean validateInput(int iOldAction, int iNewAction) {
        if (iOldAction == ACTION_NONE && (iNewAction == ACTION_ADD_COPY ||
                                          iNewAction == ACTION_MODIFY ||
                                          iNewAction == ACTION_REMOVE)) {
            if (tblValue.getSelectedRow() < 0) {
                return false;
            }
        } else if ((iOldAction == ACTION_ADD || iOldAction == ACTION_ADD_COPY ||
                    iOldAction == ACTION_MODIFY) && iNewAction == ACTION_SAVE) {
            return validateInput();
        }
        return true;

    }

    public void onChangeAction(int iOldAction, int iNewAction) {
        if (iNewAction == ACTION_NONE) {
            formData.setFieldEnabled(false);
	    area.txtCode.setEnabled(false);
            tblValue2.setEnabled(true);
            tblValue2.requestFocus();
            checkControlButton();
        } else if (iNewAction == ACTION_SAVE || iNewAction == ACTION_CANCEL) {
		fillDetailValue();
            checkControlButton();
        } else if (iNewAction == ACTION_ADD || iNewAction == ACTION_MODIFY ||
                   iNewAction == ACTION_ADD_COPY) {
            formData.setFieldEnabled(true);
	    area.txtCode.setEnabled(true);
            tblValue2.setEnabled(false);
            checkControlButton();
            if (iNewAction == ACTION_ADD) {
                clearDetailValue();
            }
//	    ISDN.requestFocus();
        }

    }

    public boolean add() {
        try {
            DataTransmit request = new DataTransmit();
            //Lay gia tri tu form
            request.setString("mstrID_area", area.getCode());
            request.setString("mstrIMSI", imsi_p.getText().trim());
            request.setString("mstrStartdate", start_date.getText().trim());
            request.setString("mstrFinishdate", finish_date.getText().trim());
            //day sang ben bean thuc hien truy van
            DataTransmit response = AppClient.sendRequest(
                    "telsoft.app.bean.TransportBean", "insert", request);
            Vector vtData = new Vector();
            //lay gia tri bean tra ve
            vtData.addElement(area.getName());
            vtData.addElement(response.getString("mstrIMSI"));
            vtData.addElement(response.getString("mstrStartdate"));
            vtData.addElement(response.getString("mstrFinishdate"));
            vtData.addElement(area.getCode());
            tblValue2.addRow(vtData);
            if (tblValue2.getRowCount() >
                0) {
                int iSelected = tblValue2.
                                getRowCount() - 1;
                tblValue2.
                        changeSelectedRow(iSelected);
            }
            checkControlButton();
        } catch (Exception e) {
            e.printStackTrace();
            MessageBox.showMessageDialog(this, e, Global.APP_NAME,
                                         MessageBox.ERROR_MESSAGE);
//	    ISDN.requestFocus();
            return false;
        }
        return true;

    }

    public boolean modify() {
        try {
            int iSelected = tblValue2.getSelectedRow();
            if (iSelected < 0) {
                return false;
            }

            Vector vtAttribute = tblValue2.getRow(iSelected);
            DataTransmit request = new DataTransmit();
            request.setString("mstrID_area", area.getCode());
            request.setString("mstrIMSI", imsi_p.getText().trim());
            request.setString("mstrStartdate", start_date.getText().trim());
            request.setString("mstrFinishdate", finish_date.getText().trim());
	    request.setString("mstrID_map",vtAttribute.elementAt(0).toString());
//	    request.setVector("vtData", vtAttribute);
            DataTransmit response = AppClient.sendRequest(
                    "telsoft.app.bean.TransportBean", "update", request);
//	    vtAttribute = response.getVector("vtReturn");
            vtAttribute.setElementAt(area.getName().trim(), 1);
            vtAttribute.setElementAt(imsi_p.getText().trim(), 2);
            vtAttribute.setElementAt(start_date.getText(), 3);
            vtAttribute.setElementAt(finish_date.getText().trim(), 4);

            tblValue.setRow(iSelected, vtAttribute);
            if (tblValue.getRowCount() >
                0) {
                if (iSelected < 0 ||
                    iSelected >=
                    tblValue.getRowCount()) {
                    iSelected = 0;
                }
                tblValue.
                        changeSelectedRow(iSelected);
            }
        } catch (Exception e) {
            e.printStackTrace();
            MessageBox.showMessageDialog(this, e, Global.APP_NAME,
                                         MessageBox.ERROR_MESSAGE);
//	     txtCode.requestFocus();
            return false;
        }
        return true;

    }

    public boolean remove() {
        return false;
    }

    public boolean search() {
        return false;
    }

    public String getPermission() {
        return telsoft.admin.util.AppClient.getPermission(PermissionApp.
                FormTransport);
    }


}
